package org.example.configurature;

import com.bianmaba.commons.bean.result.OperationResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity translate(Exception e) {
        if (OAuth2Exception.class.isAssignableFrom(e.getClass())) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
            OperationResult result = OperationResult.of(false, "资源请求失败，" + oAuth2Exception.getLocalizedMessage() + "，请联系管理员授权！");
            result.setStatus(oAuth2Exception.getHttpErrorCode(), oAuth2Exception.getLocalizedMessage());
            ResponseEntity response = new ResponseEntity(result, HttpStatus.valueOf(oAuth2Exception.getHttpErrorCode()));
            return response;
        } else {
            OperationResult result = OperationResult.of(false, "资源请求失败，认证失败，请联系管理员授权！");
            result.setStatus(400, "Bad Request");
            ResponseEntity response = new ResponseEntity(result, HttpStatus.valueOf(400));
            return response;
        }
    }
}